package de.dushuhu.dyndns;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Inject;
import com.google.inject.name.Named;

public class UpdateServiceImpl implements UpdateService {

	private static final Logger logger = LoggerFactory
			.getLogger(UpdateServiceImpl.class);

	private String address;

	private Integer port;

	@Inject
	public UpdateServiceImpl(@Named(DYNDNS_SERVER_ADDRESS) String address,
			@Named(DYNDNS_SERVER_PORT) Integer port) {
		this.address = address;
		this.port = port;
	}

	public void update(String hostAddress, String hostname, String username,
			String password) throws IOException {

		String currentAdress = InetAddress.getByName(hostname).getHostAddress();
		if (currentAdress.equals(hostAddress)) {
			logger.trace("skipped unchanged ip " + hostAddress);
			return;
		}

		DefaultHttpClient httpclient = new DefaultHttpClient();
		try {
			httpclient.getCredentialsProvider().setCredentials(
					new AuthScope(address, port, AuthScope.ANY_REALM),
					new UsernamePasswordCredentials(username, password));

			String uri = "http://" + address + ":" + port
					+ "/nic/update?hostname=" + hostname + "&myip="
					+ hostAddress;
			System.out.println(uri);
			HttpGet httpget = new HttpGet(uri);

			System.out.println("executing request" + httpget.getRequestLine());
			HttpResponse response = httpclient.execute(httpget);
			System.out.println("----------------------------------------");
			System.out.println(response.getStatusLine());

			logger.info(response.getStatusLine().toString());

			HttpEntity entity = response.getEntity();
			if (entity != null) {
				System.out.println("Response content length: "
						+ entity.getContentLength());
			}

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					entity.getContent()));
			String line = reader.readLine();
			while (line != null) {
				logger.info(line);
				line = reader.readLine();
			}

		} finally {
			// When HttpClient instance is no longer needed,
			// shut down the connection manager to ensure
			// immediate deallocation of all system resources
			httpclient.getConnectionManager().shutdown();
		}

		return;
	}

}
